package com.vois.jack.btmgr.devices.BBSerial;

import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothProfile;
import android.os.Bundle;
import android.os.Message;
import android.os.ParcelUuid;
import android.text.TextUtils;

import com.vois.jack.btmgr.blebase.BleAction;
import com.vois.jack.btmgr.blebase.BleConstant;
import com.vois.jack.btmgr.blebase.BleDevCommonMsg;
import com.vois.jack.btmgr.blebase.BleDevice;
import com.vois.jack.btmgr.blebase.BleDeviceFsm;
import com.vois.jack.btmgr.classicbase.BtRecorderInterface;
import com.vois.jack.btmgr.common.IBtConstants;
import com.vois.jack.btmgr.util.ActionProcessUtil;
import com.vois.jack.btmgr.util.Logger;

import java.util.Arrays;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class BBSerialBleDevice extends BleDevice {
    private Logger logger = Logger.getLogger(BBSerialBleDevice.class);
    private final static String DEFAULT_PASSWORD = "123456";
    private final static UUID BLE_KEY_SERVICE_UUID = UUID.fromString("d000f000-0001-a000-b000-000000000000");
    private final static UUID BLE_KEY_GET_UUID = UUID.fromString("d000f001-0001-a000-b000-000000000000");
    private final static UUID BLE_KEY_SET_UUID = UUID.fromString("d000f002-0001-a000-b000-000000000000");
    private final static UUID BLE_KEY_BTN_UUID = UUID.fromString("d000f003-0001-a000-b000-000000000000");
    private final static UUID BLE_KEY_VERIFICATION_UUID = UUID.fromString("d000f004-0001-a000-b000-000000000000");
    private final static String EXTRA_RESULT_DATA = "action_result_data";

    public final static String EXTRA_BATTERY_VALUE = "battery_value";
    public final static String EXTRA_BBSERIAL_VERSION = "bbserial_version";

    private int verifyTry;
    private boolean isTryingVerify;
    private ActionProcessUtil actionProcessUtil;
    private Map<String, Boolean> bleHasPttKeyDownMap = new ConcurrentHashMap<>();

    public interface BBSerialActionCallback {
        void onActionResult(String result, int status);
    }

    @Override
    public boolean openBleDevice(boolean shouldStartWithScan) {
        boolean ret = super.openBleDevice(shouldStartWithScan);
        actionProcessUtil = new ActionProcessUtil("BBSerialAction", getBleDeviceFsm().getHandler());
        actionProcessUtil.startActionExecution();
        return ret;
    }

    @Override
    public boolean closeBleDevice() {
        boolean ret = super.closeBleDevice();
        actionProcessUtil.stopActionExecution();
        actionProcessUtil = null;

        return ret;
    }

    @Override
    public void getValidationData() {
        actionProcessUtil.addActionRequest(this, null, 5000, new ActionProcessUtil.ActionCallback() {
            @Override
            public boolean onProcess(Object context, Bundle parameters) {
                byte[] data = getCmdData(BBSerialBleCmd.BLE_KEY_CMD_GET_ID, null);
                logger.d( "getId onProcess: send command:" + new String(data));
                writeCharacteristicData(BLE_KEY_SERVICE_UUID, getCharacterUUID(BBSerialBleCmd.BLE_KEY_CMD_GET_ID), data, data.length, new BleAction.BleActionCallback() {
                    @Override
                    public void onActionResult(int status, Bundle result) {

                    }
                });
                return true;
            }

            @Override
            public void onResult(Object context, Bundle data) {
                logger.d( "getId onResult: ");
                String ret = parseResultOfCmd(data.getByteArray(EXTRA_RESULT_DATA),"(ID):(.*);", BBSerialBleCmd.BLE_KEY_CMD_GET_ID);
                final BleDeviceListener listener = getListener();
                if (listener != null) {
                    final String seqId = (TextUtils.isEmpty(ret) ? "" : ret);
                    Message message = Message.obtain();
                    message.what = BleDevCommonMsg.BLE_DEV_COMMON_VALIDATION_RESULT.getValue();
                    Bundle bundle = new Bundle();
                    bundle.putString(BleConstant.EXTRA_SEQID, seqId);
                    message.setData(bundle);
                    listener.onMessage(getBluetoothDevice(), message);
                }
            }

            @Override
            public void onError(Object context, int errorCode) {

            }

            @Override
            public void onTimeout(Object context) {

            }
        });
    }

    @Override
    public void getAddress() {
        actionProcessUtil.addActionRequest(this, null, 5000, new ActionProcessUtil.ActionCallback() {
            @Override
            public boolean onProcess(Object context, Bundle parameters) {
                byte[] data = getCmdData(BBSerialBleCmd.BLE_KEY_CMD_GET_MAC, null);
                logger.d( "getAddress onProcess: send command:" + new String(data));
                writeCharacteristicData(BLE_KEY_SERVICE_UUID, getCharacterUUID(BBSerialBleCmd.BLE_KEY_CMD_GET_MAC), data, data.length, new BleAction.BleActionCallback() {
                    @Override
                    public void onActionResult(int status, Bundle result) {

                    }
                });
                return true;
            }

            @Override
            public void onResult(Object context, Bundle data) {
                logger.d( "getAddress onResult: ");
                String ret = parseResultOfCmd(data.getByteArray(EXTRA_RESULT_DATA),"(MAC):(.*);", BBSerialBleCmd.BLE_KEY_CMD_GET_MAC);
                final BleDeviceListener listener = getListener();
                if (listener != null) {
                    final String address = (TextUtils.isEmpty(ret) ? "" : ret);
                    Message message = Message.obtain();
                    message.what = BleDevCommonMsg.BLE_DEV_COMMON_GET_ADDRESS_RESULT.getValue();
                    Bundle bundle = new Bundle();
                    bundle.putString(BleConstant.EXTRA_ADDRESS, address);
                    message.setData(bundle);
                    listener.onMessage(getBluetoothDevice(), message);
                }
            }

            @Override
            public void onError(Object context, int errorCode) {

            }

            @Override
            public void onTimeout(Object context) {

            }
        });
    }

    public BBSerialBleDevice() {
        super();
        verifyTry = 0;
        setNeedVerified(true);
        setFullReConnectProcessFirst(true);
        setConnectingTimeout(20000);
        setConnectTryTimes(2);
        setScanTimeout(60000);
        setScanTryTimes(2);
        setFullConnectTryTimes(10);
    }

    private UUID getCharacterUUID(BBSerialBleCmd cmd) {
        switch (cmd){
            case BLE_KEY_CMD_GET_PASSWORD:
            case BLE_KEY_CMD_GET_MAC:
            case BLE_KEY_CMD_GET_BAT:
            case BLE_KEY_CMD_GET_NAME:
            case BLE_KEY_CMD_GET_VERSION:
            case BLE_KEY_CMD_GET_ID:
                return BLE_KEY_GET_UUID;
            case BLE_KEY_CMD_SET_KEY_LONG_TIME:
            case BLE_KEY_CMD_SET_BROADCAST_PARA:
            case BLE_KEY_CMD_SET_CONNECT_PARA:
            case BLE_KEY_CMD_SET_PASSWORD:
            case BLE_KEY_CMD_SET_RECONNECT_PARA:
            case BLE_KEY_CMD_SET_NAME:
            case BLE_KEY_CMD_SET_ID:
                return BLE_KEY_SET_UUID;
            case BLE_KEY_CMD_GET_MAC_ID:
            case BLE_KEY_CMD_VERIFICATION:
                return BLE_KEY_VERIFICATION_UUID;
            default:
                return null;
        }
    }

    private byte[] getCmdData(BBSerialBleCmd cmd, byte[] data) {
        byte[] startCmd = null, endCmd = null;
        switch (cmd){
            case BLE_KEY_CMD_GET_PASSWORD:
                return "Getpass;".getBytes();
            case BLE_KEY_CMD_GET_MAC:
                return "Getmacid;".getBytes();
            case BLE_KEY_CMD_GET_BAT:
                return "Getbat;".getBytes();
            case BLE_KEY_CMD_GET_NAME:
                return "Getname;".getBytes();
            case BLE_KEY_CMD_GET_VERSION:
                return "Getversion;".getBytes();
            case BLE_KEY_CMD_GET_ID:
                return "GetID;".getBytes();

            case BLE_KEY_CMD_GET_MAC_ID:
                return "Getmacid;".getBytes();

            case BLE_KEY_CMD_SET_KEY_LONG_TIME:
                startCmd = "Setkeylt:".getBytes();
                endCmd = ";".getBytes();
                break;
            case BLE_KEY_CMD_SET_BROADCAST_PARA:
                startCmd = "Setadvpra:".getBytes();
                endCmd = ";".getBytes();
                break;
            case BLE_KEY_CMD_SET_CONNECT_PARA:
                startCmd = "Setconpra:".getBytes();
                endCmd = ";".getBytes();
                break;
            case BLE_KEY_CMD_SET_PASSWORD:
                startCmd = "Setpass:".getBytes();
                endCmd = ";".getBytes();
                break;
            case BLE_KEY_CMD_SET_RECONNECT_PARA:
                startCmd = "Setcnag:".getBytes();
                endCmd = ";".getBytes();
                break;
            case BLE_KEY_CMD_SET_NAME:
                startCmd = "Setna:".getBytes();
                endCmd = ";".getBytes();
                break;
            case BLE_KEY_CMD_SET_ID:
                startCmd = "SetID:".getBytes();
                endCmd = ";".getBytes();
                break;
            case BLE_KEY_CMD_VERIFICATION:
                startCmd = "PS:".getBytes();
                break;
        }
        int len = (startCmd != null ? startCmd.length : 0) + (data != null ? data.length : 0) + (endCmd != null ? endCmd.length : 0);
        if(len > 0){
            byte[] result = new byte[len];
            int index = 0;
            if(startCmd != null){
                System.arraycopy(startCmd, 0, result, index, startCmd.length);
                index += startCmd.length;
            }
            if(data != null){
                System.arraycopy(data, 0, result, index, data.length);
                index += data.length;
            }
            if(endCmd != null){
                System.arraycopy(endCmd, 0, result, index, endCmd.length);
                index += endCmd.length;
            }
            return result;
        }else{
            return  null;
        }
    }
    private String bytes2HexString(byte[] array) {
        StringBuilder builder = new StringBuilder();

        for (byte b : array) {
            String hex = Integer.toHexString(b & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            builder.append(hex);
        }

        return builder.toString().toUpperCase();
    }

    private boolean keyGen(byte[] pRandom, byte[] key) {
        if(pRandom.length != 4 || key == null)
            return false;

        Arrays.fill(key, (byte)0xad);

        key[0] = (byte)pRandom[3];
        key[10] = (byte)(pRandom[0]^0xcc);
        key[12] = (byte)(pRandom[2]&0xea);
        key[1] = (byte)(pRandom[1]^pRandom[0]);
        key[8] = (byte)(pRandom[2]^pRandom[3]);
        key[4] = (byte)(pRandom[1]);
        key[3] = (byte)(pRandom[2]^(~pRandom[0]));
        key[2] = (byte)(pRandom[1]^pRandom[2]);
        key[5] = (byte)(key[1]^key[2]);

        return true;
    }

    private boolean getEncryptKey(String password, byte[] random, byte[] key) {
        boolean ret = false;
        if(key != null && key.length >= 16){
            keyGen(random, key);
            try {
                logger.d( "getEncryptKey: before key:" + bytes2HexString(key));
                SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
                Cipher cipher = Cipher.getInstance("AES");
                cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
                byte[] src = new byte[16];
                byte[] pwd = password.getBytes();
                System.arraycopy(pwd, 0, src, 0, Math.min(src.length, pwd.length));
                byte[] cypertext = cipher.doFinal(src, 0, 16);
                Arrays.fill(key, (byte) 0);
                System.arraycopy(cypertext, 0, key, 0, 16);
                logger.d( "getEncryptKey: after key:" + bytes2HexString(key));
                ret = true;
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return ret;
    }

    @Override
    public void onScanStateChanged(int state) {

    }

    @Override
    public void onConnectStateChanged(int state, int reason) {
        super.onConnectStateChanged(state, reason);
        if (state == BluetoothProfile.STATE_DISCONNECTED) {
            if (isTryingVerify) {
                connectBleDevice();
            }
        }
    }

    private void verifyBle() {
        logger.d( "verifyBle");
        BleAction bleAction = new BleAction();
        Bundle arg = new Bundle();
        bleAction.setCmd(BleAction.BleCmd.BLE_CMD_ENABLE_NOTIFICATION);
        arg.putParcelable(BleDeviceFsm.EXTRA_SERVICE_UUID, new ParcelUuid(BLE_KEY_SERVICE_UUID));
        arg.putParcelable(BleDeviceFsm.EXTRA_CHARACTERISTIC_UUID, new ParcelUuid(BLE_KEY_VERIFICATION_UUID));
        arg.putBoolean(BleDeviceFsm.EXTRA_ENABLE_VALUE, true);
        bleAction.setCmdArg(arg);
        bleAction.setCallback(new BleAction.BleActionCallback() {
            @Override
            public void onActionResult(int status, Bundle result) {
                logger.d( "onActionResult: status:" + status);
                if (status == BluetoothGatt.GATT_SUCCESS) {
                    Map<ParcelUuid, byte[]> map = getScanRecord().getServiceData();
                    Set<ParcelUuid> list = map.keySet();
                    byte[] randomData = null;

                    for (ParcelUuid uuid: list) {
                        short shortUUID = (short) ((uuid.getUuid().getMostSignificantBits() & 0x0000FFFF00000000L) >> 32);
                        if (shortUUID == 0x180a) {
                            randomData = getScanRecord().getServiceData(uuid);
                            break;
                        }
                    }

                    if (randomData != null) {
                        byte[] key = new byte[16];
                        if (getEncryptKey(DEFAULT_PASSWORD, randomData, key)) {
                            byte[] sendData = getCmdData(BBSerialBleCmd.BLE_KEY_CMD_VERIFICATION, key);
                            if (sendData != null) {
                                writeCharacteristicData(BLE_KEY_SERVICE_UUID,
                                        getCharacterUUID(BBSerialBleCmd.BLE_KEY_CMD_VERIFICATION),
                                        sendData, 19,
                                        new BleAction.BleActionCallback() {
                                            @Override
                                            public void onActionResult(int status, Bundle result) {
                                                logger.d( "onActionResult: write data result:" + result);
                                            }
                                        });
                            }
                        }
                    }
                }
            }
        });

        getBleDeviceFsm().executeBleAction(bleAction);
    }

    private void initBBDeviceUUID() {
        BleAction bleAction = new BleAction();
        Bundle args = new Bundle();
        args.putParcelable(BleDeviceFsm.EXTRA_SERVICE_UUID, new ParcelUuid(BLE_KEY_SERVICE_UUID));
        args.putParcelable(BleDeviceFsm.EXTRA_CHARACTERISTIC_UUID, new ParcelUuid(BLE_KEY_BTN_UUID));
        args.putBoolean(BleDeviceFsm.EXTRA_ENABLE_VALUE, true);
        bleAction.setCmd(BleAction.BleCmd.BLE_CMD_ENABLE_NOTIFICATION);
        bleAction.setCmdArg(args);
        bleAction.setCallback(new BleAction.BleActionCallback() {
            @Override
            public void onActionResult(int status, Bundle result) {
                if (status == BluetoothGatt.GATT_SUCCESS) {
                    BleAction keySetAction = new BleAction();
                    Bundle keySetArgs = new Bundle();
                    keySetArgs.putParcelable(BleDeviceFsm.EXTRA_SERVICE_UUID, new ParcelUuid(BLE_KEY_SERVICE_UUID));
                    keySetArgs.putParcelable(BleDeviceFsm.EXTRA_CHARACTERISTIC_UUID, new ParcelUuid(BLE_KEY_SET_UUID));
                    keySetArgs.putBoolean(BleDeviceFsm.EXTRA_ENABLE_VALUE, true);
                    keySetAction.setCmd(BleAction.BleCmd.BLE_CMD_ENABLE_NOTIFICATION);
                    keySetAction.setCmdArg(keySetArgs);
                    keySetAction.setCallback(new BleAction.BleActionCallback() {
                        @Override
                        public void onActionResult(int status, Bundle result) {
                            if (status == BluetoothGatt.GATT_SUCCESS) {
                                BleAction keyGetAction = new BleAction();
                                Bundle keyGetArgs = new Bundle();
                                keyGetArgs.putParcelable(BleDeviceFsm.EXTRA_SERVICE_UUID, new ParcelUuid(BLE_KEY_SERVICE_UUID));
                                keyGetArgs.putParcelable(BleDeviceFsm.EXTRA_CHARACTERISTIC_UUID, new ParcelUuid(BLE_KEY_GET_UUID));
                                keyGetArgs.putBoolean(BleDeviceFsm.EXTRA_ENABLE_VALUE, true);
                                keyGetAction.setCmd(BleAction.BleCmd.BLE_CMD_ENABLE_NOTIFICATION);
                                keyGetAction.setCmdArg(keyGetArgs);
                                keyGetAction.setCallback(new BleAction.BleActionCallback() {
                                    @Override
                                    public void onActionResult(int status, Bundle result) {
                                        if (status == BluetoothGatt.GATT_SUCCESS) {
                                            if (getListener() != null) {
                                                getListener().onReady(getBluetoothDevice());
                                            }
                                        }
                                    }
                                });

                                getBleDeviceFsm().executeBleAction(keyGetAction);
                            }
                        }
                    });

                    getBleDeviceFsm().executeBleAction(keySetAction);
                }
            }
        });

        getBleDeviceFsm().executeBleAction(bleAction);
    }

    @Override
    public void onVerifying() {
        logger.d( "onVerifying: ");
        verifyBle();
    }

    @Override
    public void onReady() {
        logger.d( "onReady: ");
        initBBDeviceUUID();
    }

    @Override
    public void onError(int errorCause) {

    }

    @Override
    public void onCharacteristiChanged(UUID serviceUUID, UUID characteristicUUID, byte[] data) {
        logger.d( "onCharacteristiChanged");
        if(characteristicUUID.equals(BLE_KEY_VERIFICATION_UUID)) {
            logger.d( "onCharacteristicChanged: BLE_KEY_VERIFICATION_UUID");
            String str = new String(data);

            Pattern pattern = Pattern.compile("(PairRes):(\\d{1});");
            Matcher matcher = pattern.matcher(str);
            if(matcher.find()) {
                int verify = Integer.valueOf(matcher.group(2));
                if(verify == 1) {
                    getBleDeviceFsm().reportVerifyResult(0, null);
                    logger.d( "onResult: verify succ");
                }else{
                    logger.d( "onResult: verify fail");
                    if (verifyTry < 3) {
                        isTryingVerify = true;
                    }else {
                        isTryingVerify = false;
                        verifyTry = 0;
                        getBleDeviceFsm().reportVerifyResult(-1, "try 3 times failed!");
                    }

                    disconnectBleDevice();
                }
            }
        }else if(characteristicUUID.equals(BLE_KEY_GET_UUID)) {
            logger.d( "onCharacteristicChanged: BLE_KEY_GET_UUID");
            Bundle result = new Bundle();
            result.putByteArray(EXTRA_RESULT_DATA, data);
            actionProcessUtil.reportResult(this, result);
        }else if(characteristicUUID.equals(BLE_KEY_SET_UUID)) {
            logger.d( "onCharacteristiChanged: BLE_KEY_SET_UUID");
            Bundle result = new Bundle();
            result.putByteArray(EXTRA_RESULT_DATA, data);
            actionProcessUtil.reportResult(this, result);
        }else if(characteristicUUID.equals(BLE_KEY_BTN_UUID)) {
            String str = new String(data);
            logger.d( "onCharacteristicChanged: onKey:" + str);
            Pattern pattern = Pattern.compile("(PCBKEY):(\\d{1});");
            Matcher matcher = pattern.matcher(str);
            if(matcher.find()) {
                int pressed = Integer.valueOf(matcher.group(2));
                Message message = Message.obtain();

                if(pressed == 1) {
                    message.what = BleDevCommonMsg.BLE_DEV_COMMON_KEY_PRESSED_MSG.getValue();
                    Bundle bundle = new Bundle();
                    bundle.putInt(BleConstant.EXTRA_KEY_CODE, BleConstant.KEY_PTT);
                    message.setData(bundle);
                }else if(pressed == 0) {
                    message.what = BleDevCommonMsg.BLE_DEV_COMMON_KEY_RELEASED_MSG.getValue();
                    Bundle bundle = new Bundle();
                    bundle.putInt(BleConstant.EXTRA_KEY_CODE, BleConstant.KEY_PTT);
                    message.setData(bundle);
                }

                BleDeviceListener listener = getListener();
                if (listener != null) {
                    listener.onMessage(getBluetoothDevice(), message);
                }
            }
        }
    }

    @Override
    public void onReliableWriteCompleted(int status) {

    }

    public void getBattery() {
        actionProcessUtil.addActionRequest(this, null, 5000, new ActionProcessUtil.ActionCallback() {
            @Override
            public boolean onProcess(Object context, Bundle parameters) {
                logger.d( "getBattery onProcess: ");
                byte[] data = getCmdData(BBSerialBleCmd.BLE_KEY_CMD_GET_BAT, null);
                if (data != null) {
                    writeCharacteristicData(BLE_KEY_SERVICE_UUID, getCharacterUUID(BBSerialBleCmd.BLE_KEY_CMD_GET_BAT), data, data.length, new BleAction.BleActionCallback() {
                        @Override
                        public void onActionResult(int status, Bundle result) {
                        }
                    });
                }

                return true;
            }

            @Override
            public void onResult(Object context, Bundle data) {
                logger.d( "getBattery onResult: ");
                String ret = parseResultOfCmd(data.getByteArray(EXTRA_RESULT_DATA),"(BAT):(\\d{3});", BBSerialBleCmd.BLE_KEY_CMD_GET_BAT);

                if (ret != null) {
                    int batteryValue = Integer.valueOf(ret);

                    BleDeviceListener listener;
                    listener = getListener();
                    if (listener != null) {
                        Message message = Message.obtain();
                        Bundle bundle = new Bundle();
                        message.what = BBSerialBleMsg.BBSERAIL_GET_BATTERY_RET.getValue();
                        bundle.putInt(EXTRA_BATTERY_VALUE, batteryValue);
                        message.setData(bundle);
                        listener.onMessage(getBluetoothDevice(), message);
                    }
                }
            }

            @Override
            public void onError(Object context, int errorCode) {

            }

            @Override
            public void onTimeout(Object context) {

            }
        });
    }

    @Override
    public void getVersion() {
        actionProcessUtil.addActionRequest(this, null, 5000, new ActionProcessUtil.ActionCallback() {
            @Override
            public boolean onProcess(Object context, Bundle parameters) {
                byte[] data = getCmdData(BBSerialBleCmd.BLE_KEY_CMD_GET_VERSION, null);
                logger.d( "getVersion onProcess: send command:" + new String(data));
                writeCharacteristicData(BLE_KEY_SERVICE_UUID, getCharacterUUID(BBSerialBleCmd.BLE_KEY_CMD_GET_VERSION), data, data.length, new BleAction.BleActionCallback() {
                    @Override
                    public void onActionResult(int status, Bundle result) {

                    }
                });
                return true;
            }

            @Override
            public void onResult(Object context, Bundle data) {
                logger.d( "getVersion onResult: ");
                String ret = parseResultOfCmd(data.getByteArray(EXTRA_RESULT_DATA),"(VER):(.*);", BBSerialBleCmd.BLE_KEY_CMD_GET_VERSION);
                BleDeviceListener listener = getListener();
                if (listener != null) {
                    Message message = Message.obtain();
                    Bundle bundle = new Bundle();
                    message.what = BBSerialBleMsg.BBSERAIL_GET_VERSION_RET.getValue();
                    bundle.putString(EXTRA_BBSERIAL_VERSION, ret);
                    message.setData(bundle);
                    listener.onMessage(getBluetoothDevice(), message);
                }

                if (listener != null) {
                    Message message = Message.obtain();
                    message.what = BleDevCommonMsg.BLE_DEV_COMMON_GET_VERSION_RESULT.getValue();
                    Bundle bundle = new Bundle();
                    bundle.putString(BleConstant.EXTRA_VERSION, ret);
                    message.setData(bundle);
                    listener.onMessage(getBluetoothDevice(), message);
                }
            }

            @Override
            public void onError(Object context, int errorCode) {

            }

            @Override
            public void onTimeout(Object context) {

            }
        });
    }

    private String parseResultOfCmd(byte[] value, String patternStr, BBSerialBleCmd cmd) {
        if (value != null) {
            switch (cmd){
                case BLE_KEY_CMD_GET_MAC:
                    if(value.length >= 11){//返回格式 MAC:123456;
                        return String.format("%02X%02X%02X%02X%02X%02X", value[4], value[5], value[6], value[7], value[8], value[9]);
                    }
                    break;
                default:
                    String str = new String(value);
                    Pattern pattern = Pattern.compile(patternStr);
                    Matcher matcher = pattern.matcher(str);

                    if (matcher.find()) {
                        return matcher.group(2);
                    }
            }
        }
        return "";
    }

    @Override
    public String getDeviceModel() {
        return "WL-BB Serial";
    }

    @Override
    public void setSeqID(String seqID) {

    }

    @Override
    public void getVendor() {

    }

    @Override
    public String getProtocolName() {
        return IBtConstants.PROTOCOL_ZHIXIN;
    }

    @Override
    public int getSampleRate() {
        return 0;
    }

    @Override
    public boolean startRecorder(ResultCallback callback) {
        return false;
    }

    @Override
    public void stopRecorder(ResultCallback callback) {

    }

    @Override
    public int getDefaultRecorderType() {
        return 0;
    }

    @Override
    public BtRecorderInterface getRecorder(int recoderType) {
        return null;
    }
}
